package gsw.demo.socket;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.URLEncoder;

import javax.net.ssl.SSLSocketFactory;

import gsw.demo.R;

public class ActivitySocket extends AppCompatActivity {
    //显示请求结果
    TextView showResult;
    //Http的输出流
    BufferedWriter bw = null;
    //Https的输出流
    BufferedWriter bw2 = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket);
        init();
        initSocket();
        initSocketHttps();
    }

    private void init() {
        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.sendGet) {
                    sendGet();
                } else if (v.getId() == R.id.sendPost) {
                    sendPost();
                } else if (v.getId() == R.id.sendGetHttps) {
                    sendGetHttps();
                }
            }
        };
        findViewById(R.id.sendGet).setOnClickListener(clickListener);
        findViewById(R.id.sendPost).setOnClickListener(clickListener);
        findViewById(R.id.sendGetHttps).setOnClickListener(clickListener);
        showResult = findViewById(R.id.showResult);
        //让TextView可滑动
        showResult.setMovementMethod(ScrollingMovementMethod.getInstance());
    }

    /**
     * 建立Socket连接
     */
    private void initSocket() {
        //读数据
        new Thread() {
            @Override
            public void run() {
                try {
                    Socket socket = new Socket("restapi.amap.com", 80);
                    //接受数据的输入流
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    String line = null;
                    final StringBuffer sb = new StringBuffer();
                    while ((line = br.readLine()) != null) {
                        System.out.println("recv :" + line);
                        sb.append(line + "\n");
                    }
                    showReult(showResult, sb.toString());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 建立Https的Socket连接
     * 使用SSLSocketFactory来创建Https的Socket，端口为443
     */
    private void initSocketHttps() {
        //读数据
        new Thread() {
            @Override
            public void run() {
                try {
                    Socket socket = SSLSocketFactory.getDefault().createSocket("www.baidu.com", 443);
                    //接受数据的输入流
                    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    bw2 = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                    String line = null;
                    final StringBuffer sb = new StringBuffer();
                    while ((line = br.readLine()) != null) {
                        sb.append(line + "\n");
                        showReult(showResult, sb.toString());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 发送get请求
     */
    private void sendGet() {
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    //请求首行
                    bw.write("GET /v3/weather/weatherInfo?city=长沙&key=13cb58f5884f9749287abbead9c658f2 HTTP/1.1\r\n");
                    //请求头
                    bw.write("Host: restapi.amap.com\r\n");
                    //请求空行
                    bw.write("\r\n");
                    bw.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 发送Post请求
     */
    private void sendPost() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String data = URLEncoder.encode("city", "utf-8") + "=" + URLEncoder.encode("长沙", "utf-8") + "&" +
                            URLEncoder.encode("key", "utf-8") + "=" + URLEncoder.encode("13cb58f5884f9749287abbead9c658f2", "utf-8");
                    //请求首行
                    bw.write("POST /v3/weather/weatherInfo HTTP/1.1\r\n");
                    //请求头
                    bw.write("Host: restapi.amap.com\r\n");
                    bw.write("Content-Length: " + data.length() + "\r\n");
                    bw.write("Content-Type: application/x-www-form-urlencoded\r\n");
                    //请求空行
                    bw.write("\r\n");
                    //请求体
                    bw.write(data);
                    bw.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * Https的get请求
     */
    private void sendGetHttps() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    bw2.write("GET / HTTP/1.1\r\n");
                    bw2.write("Host: www.baidu.com\r\n");
                    bw2.write("\r\n");
                    bw2.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 显示请求结果
     */
    private void showReult(final TextView tv, final String result) {
        tv.post(new Runnable() {
            @Override
            public void run() {
                tv.setText(result);
            }
        });
    }
}
